<template>
  <div
    class="contractList"
    v-loading="pictLoading"
    element-loading-background="rgba(0, 0, 0, 0.5)"
    element-loading-text="正在生成dyned账号......"
  >
    <el-card>
      <!-- <div class="opt_wrap">
            <el-button type="text" @click="goToURL2('contractDetails',{pageType:'create',type_id})">
                <i class="iconfont icon-add"></i>
                新增{{typeTitle}}
            </el-button>
        </div> -->
      <div class="opt_wrap">
        <div class="opt_wrap_left">
          <p>
            已选中<span style="color: #1796EB">{{ selectedNum }}</span
            >项
          </p>
          <p v-if="showBtn" @click="showDelModal = true">
            <i class="iconfont icon-shanchu1"></i>
            删除
          </p>
          <p
            v-if="showBtn && selectedNum === 1"
            @click="changeStatusModal = true"
          >
            <i class="iconfont icon-genggai"></i>
            更改状态
          </p>
        </div>
        <div class="opt_wrap_right">
          <p>
            <i class="iconfont icon-daochu"></i>
            导出
          </p>
          <p
            class="add"
            @click="
              goToURL2('contractDetails', {
                pageType: 'create',
                type_id,
                product
              })
            "
          >
            <i
              class="iconfont icon-xinjian1"
              style="color: white; font-size: 12px; margin-right: 4px;"
            ></i>
            新增
          </p>
        </div>
      </div>
      <statisticsTag
        :data="statisticsTagData"
        @searchStatus="searchStatus"
        v-if="statisticsTagData.length"
      />
      <div class="search_wrap">
        <el-input
          placeholder="合同编号/学员名称/手机号/邮箱"
          v-model="searchCondition"
          clearable
          style="width: 260px;"
          @keyup.enter.native="queryListData"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-date-picker
          v-model="queryDate"
          @change="queryListData"
          type="daterange"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
        <el-select
          v-model="contract_status"
          multiple
          filterable
          allow-create
          default-first-option
          @change="queryListData"
          placeholder="请选择合同状态"
        >
          <el-option
            v-for="item in contractStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div class="table_list">
        <el-table
          :data="tableListData"
          min-height="500"
          border
          v-loading="loading"
          @selection-change="handleSelectionNiche"
          style="width: 100%"
        >
          <el-table-column type="selection" align="center" width="40" />
          <el-table-column
            v-for="(item, index) in tableCaption"
            :key="index"
            :label="item.label"
            align="center"
            :width="item.width ? item.width : ''"
          >
            <template slot-scope="scope">
              <span
                class="flag"
                :style="{ background: scope.row[item.value].c }"
                v-if="item.value == 'status_arr'"
                >{{ scope.row[item.value].a }}</span
              >
              <span
                class="customer_name"
                v-else-if="item.value === 'name'"
                @click="
                  goToURL('contractDetails', {
                    pageType: 'edit',
                    id: scope.row.id,
                    product
                  })
                "
                >{{ scope.row[item.value] }}</span
              >
              <span v-else>{{ scope.row[item.value] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="dyned状态" align="center" width="110">
            <template slot-scope="scope">
              <!-- dyned_id==0未生成账号， -->
              <el-button
                type="text"
                size="small"
                v-if="scope.row.dyned_id == 0"
                @click="createAccount(scope.row.id)"
                >生成 dyned 账号</el-button
              >
              <el-button
                type="text"
                size="small"
                v-else
                @click="
                  goToURL('dynedAccountDetails', {
                    pageType: 'details',
                    id: scope.row.dyned_id,
                    product
                  })
                "
                >查看 dyned 详情</el-button
              >
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" align="center"  width="94">
                    <template slot-scope="scope">
                        <el-row type="flex" align="center">
                            <el-col :span="12" >
                                <el-button type="text"  size="small" circle  @click="goToURL('contractDetails',{pageType:'edit',id:scope.row.id})">编辑</el-button>
                            </el-col>
                            <el-col :span="12" >
                                <el-button type="text" size="small" circle  @click="handleDelete(scope.row.id)">删除</el-button>
                            </el-col>
                        </el-row>
            　　　　</template>
                </el-table-column> -->
        </el-table>
        <link-pagination
          :total="total"
          :currentPage="currentPage"
          :limit="limit"
          v-if="total != 0"
          @pagination="getPaginationParams"
        ></link-pagination>
      </div>
    </el-card>
    <!-- 更改合同状态 -->
    <el-dialog
      title="选择更改合同状态"
      width="350px"
      :visible.sync="changeStatusModal"
      class="del_modal"
    >
      <div class="content" style="display: flex; justify-content: center;">
        <el-select v-model="contractStatus" placeholder="请选择合同状态">
          <el-option
            v-for="item in contractStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div class="btn">
        <el-button @click="changeStatusModal = false">返回</el-button>
        <el-button type="primary" @click="confirmChangeContractStatus"
          >提交</el-button
        >
      </div>
    </el-dialog>
    <!-- 删除对话框 -->
    <el-dialog
      title="提示"
      width="510px"
      :visible.sync="showDelModal"
      class="del_modal"
    >
      <div class="content">
        <p><i class="iconfont icon-tishi"></i></p>
        <!-- <p v-if="selectionCustomer.length === 1">是否将客户<span>{{ selectionCustomer[0].name }}删除？</span></p>
            <p v-if="selectionCustomer.length > 1">是否将<span>{{ selectionCustomer[0].name }}、{{ selectionCustomer[1].name }}<span v-if="selectionCustomer.length > 2">等</span>{{ selectionCustomer.length }}位客户删除？</span></p> -->
        <p>删除成功之后，该操作将无法恢复</p>
      </div>
      <div class="btn">
        <el-button @click="showDelModal = false">返回</el-button>
        <el-button type="primary" @click="confirmDelete">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="提示"
      width="510px"
      :visible.sync="showDynedDialog"
      class="del_modal"
    >
      <div class="content">
        <el-form
          :model="dynedFormData"
          :rules="dynedFormRul"
          ref="dynedFormFef"
          label-width="120px"
        >
          <el-form-item label="voucher code" prop="code">
            <el-input v-model="dynedFormData.code"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="btn">
        <el-button @click="showDynedDialog = false">返回</el-button>
        <el-button type="primary" @click="confirmCreateDyned">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import statisticsTag from "@/components/statisticsTag";
import http from "@/api/contract";
import contractAuditHttp from "@/api/contract_audit";
import dynedApi from "@/api/dyned";
import { changeTitleMinin, deleteMixin, paginationMixin } from "@/mixin";
import { formatDate } from "@/utils";
export default {
  name: "contractList",
  mixins: [changeTitleMinin, deleteMixin, paginationMixin],
  data() {
    return {
      pictLoading: false,
      product: null,
      dynedFormData: {
        code: ""
      },
      dynedFormRul: {
        code: [
          { required: true, message: "请输入voucher code", trigger: "blur" }
          //   { pattern: /^[a-zA-Z0-9]{8}$/, message: "请输入正确的验证码", trigger: "blur" }
        ]
      },
      dynedid: null,
      showDynedDialog: false,
      showDelModal: false,
      selectionCustomer: null,
      contractStatus: null,
      classList: [],
      http: http,
      tableListData: [],
      tableCaption: [],
      loading: false,
      changeStatusModal: false,
      searchCondition: null,
      queryDate: null,
      statisticsTagData: [],
      optionsData: [
        {
          label: "未付全款待确认",
          total: 10,
          status: "non-payment",
          icon: "icon-weifukuan-",
          backgroundStart: "#17B5EB",
          backgroundEnd: "#1797EB"
        },
        {
          label: "已付全款待确认",
          total: 110,
          icon: "icon-yifukuan",
          backgroundStart: "#F27450",
          backgroundEnd: "#F25751"
        },
        {
          label: "执行中",
          total: 100000,
          icon: "icon-zhihangzhong",
          backgroundStart: "#FFC41F",
          backgroundEnd: "#FFA41E"
        },
        {
          label: "即将到期",
          total: 0,
          icon: "icon-jijiangdaoqi",
          backgroundStart: "#A946EB",
          backgroundEnd: "#A946EB"
        },
        {
          label: "已结束",
          total: 0,
          icon: "icon-yijieshu",
          backgroundStart: "#02C779",
          backgroundEnd: "#02C765"
        },
        {
          label: "已终止",
          total: 0,
          icon: "icon-yizhongzhi",
          backgroundStart: "#999",
          backgroundEnd: "#999"
        }
      ],
      pageParams: null,
      type_id: null, // 合同类型
      contractTypeList: [],
      contract_status: [], // 合同状态
      contractStatusList: [],
      selectedNum: 0,
      delNiche: null,
      showBtn: false,
      center_id: null,
      oldStatus: null
    };
  },
  components: {
    statisticsTag
  },
  methods: {
    // 确认更改合同状态
    confirmChangeContractStatus() {
      // let newStatus
      // for (let status of this.contractStatusList) {
      //     if (status.value === this.contractStatus) {
      //         newStatus = status.label
      //     }
      // }
      // let str = {
      //     '原合同状态': this.oldStatus,
      //     '修改合同状态': newStatus
      // }
      // let str1 = {
      //     'contract_status': this.contractStatus
      // }
      let params = {
        // center_id: this.center_id,
        // contract_id: this.selectionCustomer[0].id,
        // varname: 'contract_status',
        // varinfo: JSON.stringify(str),
        // varjson: JSON.stringify(str1),
        // remark: ''
        id: this.selectionCustomer[0].id,
        contract_status: this.contractStatus
      };
      // contractAuditHttp.createContent(params).then(res => {
      //     this.$message.success('修改合同状态申请提交成功！')
      //     this.changeStatusModal = false
      // })
      http.updateOnlyfield(params).then(res => {
        this.$message.success(res.msg || "修改合同状态成功！");
        this.changeStatusModal = false;
        this.getListData();
      });
    },
    handleSelectionNiche(val) {
      for (let status of this.contractStatusList) {
        if (val.length === 1) {
          if (status.value === val[0].contract_status) {
            this.oldStatus = status.label;
          }
        }
      }
      if (val.length) {
        this.selectionCustomer = val;
      }
      // console.log(val, val.length)
      this.selectedNum = val.length;
      if (this.selectedNum === 0) {
        this.showBtn = false;
      } else {
        this.showBtn = true;
      }
      if (this.selectionCustomer.length !== 0) {
        this.delNiche = [];
        for (let item of this.selectionCustomer) {
          this.delNiche.push(item.id);
        }
      }
      this.delNiche = JSON.parse(JSON.stringify(this.delNiche));
    },
    goToURL(name, params) {
      if (String(this.$route.query.product !== "dyned")) {
        this.$router.push({
          name,
          params,
          query: {
            showLevel: this.$route.query.showLevel,
            operation: "see",
            product: this.$route.query.product
          }
        });
      } else {
        this.$router.push({
          name,
          params,
          query: {
            showLevel: this.$route.query.showLevel,
            operation: "see",
            product: this.$route.query.product
          }
        });
      }
    },
    goToURL2(name, params) {
      // console.log(params)
      console.log(this.$route.query.showLevel);
      if (String(this.$route.query.product !== "dyned")) {
        this.$router.push({
          name,
          params,
          query: {
            showLevel: this.$route.query.showLevel,
            operation: "add",
            product: this.$route.query.product
          }
        });
      } else {
        this.$router.push({
          name,
          params,
          query: {
            showLevel: this.$route.query.showLevel,
            operation: "add",
            product: this.$route.query.product
          }
        });
      }
    },
    queryListData() {
      this.getListData();
    },
    searchStatus(status) {
      this.contract_status = [status];
      this.getListData();
    },
    // 确认删除
    confirmDelete() {
      let id = this.delNiche;
      http.deleteContent({ id }).then(res => {
        this.$message.success(res.msg || "删除成功");
        this.showDelModal = false;
        this.getListData();
      });
    },
    // 确认生成 dyned 账号
    createAccount(id) {
      console.log("this.$route.query.product", this.$route.query.product);
      if (this.product === "neo") {
        this.showDynedDialog = true;
        this.dynedid = id;
        console.log("this.dynedid", this.dynedid);
      } else {
        this.$confirm("确认生成Dyned账号吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.pictLoading = true;
            this.$message({
              type: "info",
              message: "Dyned账号生成中，请稍等"
            });
            this.showDynedDialog = false;
            dynedApi
              .createAccount({ contract_id: id })
              .then(res => {
                this.getListData();
                this.pictLoading = false;
                if (this.product === "ineo") {
                  this.$message.success("ineo账号生成成功,请前往邮箱激活");
                } else {
                  this.$message.success("Dyned账号生成成功");
                }
              })
              .catch(() => {
                this.pictLoading = false;
                this.showDynedDialog = false;
                this.$message.error("Dyned账号生成失败");
              });
          })
          .catch(() => {
            this.pictLoading = false;
            this.showDynedDialog = false;
          });
      }
    },
    // 确认生成 neo 账号
    confirmCreateDyned() {
      this.$confirm("确认生成Dyned账号吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.pictLoading = true;
          this.$message({
            type: "info",
            message: "Dyned账号生成中，请稍等"
          });
          this.showDynedDialog = false;
          dynedApi
            .createAccount({
              contract_id: this.dynedid,
              code: this.dynedFormData.code
            })
            .then(res => {
              this.getListData();
              this.pictLoading = false;
              this.$message.success("Dyned账号生成成功");
            })
            .catch(() => {
              this.pictLoading = false;
              this.showDynedDialog = false;
              this.$message.error("Dyned账号生成失败");
            });
        })
        .catch(() => {
          this.pictLoading = false;
          this.showDynedDialog = false;
        });
    },
    getListData(
      page = this.currentPage,
      list_rows = this.limit,
      search = this.searchCondition,
      type_id = this.type_id,
      contract_status = this.contract_status
    ) {
      this.loading = true;
      let params = { page, list_rows, search, type_id, contract_status };
      if (this.queryDate) {
        params["create_time_start"] = formatDate.toStr(
          new Date(this.queryDate[0]),
          "YYYY-MM-DD"
        );
        params["create_time_end"] = formatDate.toStr(
          new Date(this.queryDate[1]),
          "YYYY-MM-DD"
        );
      }
      http.getList(params).then(res => {
        this.loading = false;
        this.total = res.data.total;
        this.tableCaption = [
          {
            label: "合同编号",
            value: "contractNo",
            width: "100"
          },
          {
            label: "学员名称",
            value: "name"
          },
          {
            label: "手机号",
            value: "mobile"
          },
          {
            label: "邮箱",
            value: "email"
          },
          {
            label: "合同状态",
            value: "status_arr",
            type: "object",
            width: "136px"
          },
          {
            label: "开始日期",
            value: "start_date"
          },
          {
            label: "结束日期",
            value: "end_date"
          },
          {
            label: "创建时间",
            value: "create_time"
          }
        ];
        let tableListData = res.data.data;
        if (tableListData.length) {
          tableListData.map(item => {
            item.birthday = formatDate.toStr(
              new Date(item.birthday),
              "YYYY-MM-DD"
            );
          });
        }
        this.tableListData = tableListData;
      });
    },
    // 页面统计数据
    getContractStatus(type_id) {
      http.getContractStatus({ type_id }).then(res => {
        this.statisticsTagData = res.data;
      });
    },
    // type_id
    getPageParams(pageParamsTitle, callback) {
      if (Object.keys(this.$route.params).length) {
        sessionStorage.setItem(
          pageParamsTitle,
          JSON.stringify(this.$route.params)
        );
      }

      let pageParams = sessionStorage.getItem(pageParamsTitle);
      if (pageParams) {
        pageParams = JSON.parse(pageParams);
        this.pageParams = pageParams;
        callback();
      }
    },
    init() {
      // 获取合同状态列表
      let basicConfig = JSON.parse(sessionStorage.getItem("basicConfig"));
      let contractStatusList = [];
      let keysData = Object.keys(basicConfig.contract_status);
      if (keysData.length) {
        keysData.map(item => {
          contractStatusList.push({
            value: item,
            label: basicConfig.contract_status[item].a
          });
        });
        this.contractStatusList = contractStatusList;
      }
      let userData = JSON.parse(sessionStorage.getItem("user"));
      this.center_id = userData.center_id;

      this.getPageParams("contractListParams", () => {
        this.type_id = this.pageParams.type_id;
        this.getListData();
        this.getContractStatus(this.type_id);
      });
    },
    // 合同类型
    getContractType() {
      http.getContractType().then(res => {
        this.contractTypeList = res.data;
      });
    },
    getparams() {
      if (Object.keys(this.$route.params).length) {
        sessionStorage.setItem(
          "contractListParams1",
          JSON.stringify(this.$route.params)
        );
      }

      let pageParams = sessionStorage.getItem("contractListParams1");
      if (pageParams) {
        pageParams = JSON.parse(pageParams);
        this.showLevel = pageParams.showLevel;
        this.product = pageParams.product;
        console.log("this.product", this.product);
      }
    }
  },
  computed: {
    typeTitle() {
      let typeTitle = "";
      if (this.contractTypeList.length) {
        for (let i = 0; i < this.contractTypeList.length; i++) {
          if (this.type_id == this.contractTypeList[i].id) {
            return this.contractTypeList[i].type_name;
          }
        }
      }
      return typeTitle;
    }
  },
  created() {
    this.getContractType();
    this.init();
    this.getparams();
  },
  mounted() {
    http.getClassList().then(res => {
      this.classList = res.data;
    });
  }
};
</script>

<style lang="scss" scoped>
@import "@/assets/style/listPage.scss";

.contractList {
  // height: 100%;
  padding: 10px;
  box-sizing: border-box;
  overflow: auto;
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
    cursor: pointer;
    background: #f1f1f1;
  }

  &::-moz-scrollbar {
    display: none;
  }
  &::-ms-scrollbar {
    display: none;
  }
  &::-o-scrollbar {
    display: none;
  }

  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    width: 10px;
    cursor: pointer;
    background: #bbb;
  }
  &::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    border-radius: 0px;
    background: #f1f1f1;
  }

  .flag {
    padding: 0px 5px;
    display: inline-block;
    background: #c6c7c9;
    min-width: 100px;
    color: #fff;
    border-radius: 14px;
  }
  .customer_name {
    cursor: pointer;
    color: #409eff;
  }
  .opt_wrap {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 34px;
    &_left {
      display: flex;
      p {
        margin-right: 18px;
        color: #565656;
        font-size: 16px;
        cursor: pointer;
        &:hover {
          color: #1796eb;
        }
        &:nth-of-type(1) {
          cursor: default;
          color: #646464;
          &:hover {
            color: #646464;
          }
        }
      }
    }
    &_right {
      display: flex;
      align-items: center;
      p {
        margin-left: 18px;
        font-size: 16px;
        width: 60px;
        height: 30px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        border-radius: 5px;
        &:nth-of-type(2) {
          background: linear-gradient(top left, #17b5eb, #1796eb);
          color: white;
          &:hover {
            color: white;
          }
        }
      }
    }
  }
  .del_modal {
    .content {
      display: flex;
      flex-direction: column;
      align-items: center;
      p {
        &:nth-of-type(1) {
          width: 92px;
          height: 92px;
          border-radius: 50%;
          background: linear-gradient(to bottom, #f25851, #f27350);
          display: flex;
          justify-content: center;
          align-items: center;
          margin-bottom: 18px;
          i {
            font-size: 40px;
            color: white;
          }
        }
        &:nth-of-type(2) {
          font-size: 20px;
          color: #333;
        }
        &:nth-of-type(3) {
          font-size: 14px;
          color: #999;
          margin-top: 7px;
        }
      }
    }
  }
  .btn {
    margin-top: 30px;
    width: 100%;
    display: flex;
    justify-content: center;
    /deep/ .el-button {
      width: 214px;
    }
  }
}
</style>
